Skip to content

feat(network): add an RLPx transport on sockets and System.IO.Pipelines - #16473

Open
rubo wants to merge 23 commits into
masterfrom
feat/rlpx-pipelines-transport
Open

rubo wants to merge 23 commits into
masterfrom
feat/rlpx-pipelines-transport

Conversation

@rubo

@rubo rubo commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Changes

Fifth of the PRs that make the RLPx stack independent of DotNetty, after #15775, #15874, #16103 and #16427. This one adds an RLPx transport on sockets and System.IO.Pipelines. The hidden Network.RlpxTransport setting selects it as Sockets; DotNetty stays the default. System.IO.Pipelines ships with .NET, so nothing new is referenced.

  • Shared policy: what isn't transport-specific moves out of RlpxHost, unchanged, into internal types both hosts use: RlpxDialPolicy, RlpxSessionTracker, RlpxListener and RlpxErrorHandler.
  • Host: SocketRlpxHost accepts and dials sockets, and owns its connections until their loops end. It is a stoppable service, as RlpxHost is.
  • Connection: SocketRlpxConnection runs three loops. The receive loop fills a pipe from the socket and rents a buffer only once data arrives. The frame loop runs the handshake, then authenticates and decrypts frames, and passes nothing on before the MAC passes. The send loop encodes queued packets in batches.
  • Received packets go to ProcessingThreadCount dedicated threads, with each connection pinned to one, as on DotNetty's executor group. The size limit, Snappy, ReceiveMessage and the error handling run there in order.
  • Sending: the connection is the one owner of sending and writability, with RlpxHost's watermarks, and the host gets the close signal from it, as the refactor(network)!: give sessions a transport-neutral connection instead of the DotNetty channel #16103 review asked.
  • Crypto: each direction gets its own cipher and MAC instances, since the loops run on different threads.

Differences from DotNetty:

  • After a frame fails authentication, decoding stops and its buffers are released. DotNetty keeps decoding and logs each attempt. Static and trusted peers keep the connection either way.
  • Received packets waiting to be handled are bounded, at 16 MB per connection. Past that, the connection stops reading, so TCP slows the peer down; the pause doesn't count toward the read timeout. DotNetty queues them without limit.
  • A packet queued past the high watermark by a concurrent sender is dropped, and Enqueue returns 0. On DotNetty, senders that checked writability at the same time all get through.
  • A packet's Snappy mode and writability charge are fixed when it's queued, not when it's encoded, also under SimulateSendLatencyMs. Writability counts packet bytes only.
  • A socket that connects after its dial deadline is rejected.
  • HandshakeTimeouts counts only handshakes that run out of time on an open connection. DotNetty also counts connections that ended within 3 seconds for another reason: 971 against 16,443 on mainnet over the same hours.
  • Every received frame rents a destination buffer. DotNetty's fastest path decrypts in place; here the decryption doubles as the copy out of the pipe.
  • Disconnect details name InvalidFrameException and RlpxReadTimeoutException instead of CorruptedFrameException and ReadTimeoutException. The reasons and log levels are the same.

Testing

  • CI passes; Nethermind.Network.Test: 3,004 passed, 14 skipped.
  • The new tests run a connection on an in-memory socket against a scripted peer, with a pool that tracks every rental, so no buffer is lost or returned twice. They cover the handshake, receiving, sending, the host and its shutdown, and interop between DotNetty and sockets over loopback in both directions. Each of 38 deliberate breaks of the code fails a test. Not covered: two shutdown races that need seams in the host this PR doesn't add.
  • Two mainnet nodes on sockets ran next to master nodes, all with Lighthouse, for 15 and 22 hours. They matched master on sync time, peers, CPU, memory and bytes received. The second sent 22% less, all of it transactions served on request, which varied by up to 2.4 times between node pairs, including a pair both on DotNetty.
  • The second node ran 75fd588, before the review fixes, and never reached the 16 MB bound. One of the fixes counts each waiting packet as at least 1 KiB, so the fixed code reaches it sooner when many small packets pile up.

Benchmark

Compared with DotNetty in the same rounds:

  • Small round trips are faster: a single header takes 239 μs against 366 μs.
  • Bulk round trips are about the same: BlockBodies and ByteCodes are 2–6% faster, Receipts is 5% slower; these aren't paired comparisons.
  • Allocations drop: −32% for a single header, −31% for receipts and −68% for byte codes.
  • Per packet, a connection allocates under 0.5 KB to receive and under 120 B to send, whether the stream arrives whole or in small reads.

6 paired rounds on the CI runner (AMD EPYC 7713), with two nodes over loopback TCP and Snappy on. Times are medians; Δ is the mean of the per-round changes of the refactored DotNetty host against master, with its 99% interval. The review fixes since then change no socket benchmark significantly (run 1, run 2).

Round trip DotNetty, master DotNetty, this PR Δ 99% interval Sockets Allocated, DotNetty → sockets
SingleHeader 354.09 μs 365.52 μs +4.3% −19.3% to +27.8% 239.07 μs 7.73 → 5.24 KB
BlockBodies 16.21 ms 16.00 ms −1.1% −8.2% to +6.0% 15.63 ms 2.56 → 2.54 MB
Receipts 4.57 ms 4.00 ms −7.2% −29.4% to +15.0% 4.21 ms 21.39 → 14.74 KB
ByteCodes 11.76 ms 12.00 ms +0.6% −8.0% to +9.2% 11.31 ms 17.09 → 5.49 KB

Remarks

New public API:

  • the Network.RlpxTransport setting and its RlpxTransport enum;
  • SocketRlpxHost, public because NetworkModule in Nethermind.Init registers it. It takes the name RlpxHost once the DotNetty host is deleted.

NetworkDiagTracer stays enabled after the protocol handler tests that turn it on, and with it on, Session.MarkDisconnected throws for an inbound session that hasn't completed its handshake, before the disconnect is reported. That predates this PR; the new host tests turn the tracer off.

🤖 AI agent (Claude Code / Opus 5.5) on behalf of @rubo

rubo added 9 commits November 26, 2026 21:43
…pxHost

The socket transport that follows needs the same dial, filter, session
tracking and listener behaviour as RlpxHost. These move unchanged into
internal types both hosts can use:

- RlpxDialPolicy: the recent-IP filter with privileged IPs, and dialing a
  node's endpoint, then the other address family its verified ENR advertises
- RlpxSessionTracker: the session events, the activity observer, marking a
  session disconnected a second after its connection closes, and at shutdown
- RlpxListener: the fallback bind and the dual-mode listener socket
- RlpxErrorHandler: the logging and disconnect policy for an error in the
  communication with a peer, from ZeroNettyP2PHandler.ExceptionCaught
…Pipelines

Network.RlpxTransport (hidden, DotNetty by default) selects SocketRlpxHost,
which runs RLPx sessions without DotNetty. It shares the dial, filter and
session policy with RlpxHost, and the frame codec with the DotNetty handlers.

Each connection runs three loops. A receive loop fills a pipe from the socket,
waiting for data before it rents a buffer. A frame loop reads the pipe: the
handshake, then frames, which it authenticates, decrypts block by block into a
rented buffer and merges into packets. A send loop encodes the queued packets
in batches and writes them to the socket. Each direction has its own cipher
and MAC instances.

Received packets are handled on ProcessingThreadCount dedicated threads, each
connection pinned to one, with one FIFO per thread, as on DotNetty's executor
group: the size limit, Snappy, ReceiveMessage and the error handling, in the
order the frame loop queued them.

A packet's queue position, Snappy mode and writability charge are fixed when
it is queued, so a Hello queued before Snappy is enabled stays framed. The
connection is the one owner of writability, with DotNetty's watermarks.
A connection runs on an in-memory socket against a scripted peer that holds
the paired secrets, with a session that records what it is given and a pool
that tracks every rental. The tests cover frames split at any offset, chunks
and Snappy, failed MACs and merger errors for ordinary and privileged peers,
ordering against a reset and against an error raised by a packet, the end of
the stream mid-packet, the read and handshake timeouts, leases kept after
shutdown, ordered sends from many threads, packets larger than the batch,
short sends, the handshake without simulated latency, the encoding mode fixed
at admission, and the watermarks, checked against DotNetty's channel.

The host tests cover the listener, the inbound filter, refused, cancelled and
pending dials, and shutdown, also through the node's service stopper.

The connection takes an optional pool, a read timeout and a hook before
decoding, for these tests; its writability moves into OutboundBytes. The
handshake messages skip the simulated latency, as DotNetty writes them without
PacketSender, and the MAC processors are disposed when the connection's loops
end. An accept error other than a reset pauses the accept loop briefly.
…cket transport

A peer's Hello and its first compressed packet can arrive in one read. The
new test holds the processing thread until both are queued, then enables
Snappy while handling the Hello, as P2PProtocolHandler does, and checks the
second packet is decompressed. Deciding Snappy when the frame loop queues a
packet instead fails it. The scripted peer now RLP-encodes packet type 0.

SocketRlpxRoundTripBenchmarks runs RlpxRoundTripBenchmarks with both nodes on
the socket transport; a separate class keeps the DotNetty rows' names, so
they still compare with master's. SocketRlpxConnectionBenchmarks measures a
connection on an in-memory stream, receiving frames and sending bursts, whole
or split into small reads and sends; the peer encodes into a reused buffer
and drains without decoding, so the allocations are the connection's.
Tests for the handshake size limit at 65535 bytes with its prefix, a
handshake that completes while its ACK is still being sent, traffic in both
directions at once, a delayed packet charged when queued, a partly sent
packet charged until its last byte is sent, the dial deadline when
ConnectTimeoutMs is zero, and the ENR alternate dialed after a refused
primary, which now runs on both hosts.

SocketRlpxHost.Shutdown returns the first call's task to every caller, so a
second caller also waits for the shutdown to finish.
@claude

claude Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @rubo's task in 3m 24s —— View job


Review of PR #16473: RLPx transport on sockets and System.IO.Pipelines

  • Gather context (diff, prior comments: none)
  • Review SocketRlpxConnection / SocketRlpxHost / processing threads / pooled packets
  • Review shared policy refactor (RlpxDialPolicy, RlpxSessionTracker, RlpxListener, RlpxErrorHandler)
  • Post findings

Summary: This is careful work. The transport stays behind a hidden flag, DotNetty remains the default, and the refactor of RlpxHost moves code without changing it. I found one Medium robustness gap in the accept loop and one optional Low perf suggestion. I didn't build the code or run the tests; this is a read-only review.

Medium

  1. An exception thrown in Accept stops all inbound connections (SocketRlpxHost.cs:221, inline).

    • Accept(socket) builds the Session, raises SessionCreated synchronously (PeerManager, ProtocolsManager) and starts the connection, all inside the accept loop with no try/catch.
    • If any of that throws, the loop exits, _listenerClosed completes, and the node takes no more inbound peers until it restarts. Nothing is logged until shutdown.
    • On DotNetty, the same failure closes only that one channel.
    • TryConnect → StartSession has a smaller version of the gap: if it throws, the connection stays tracked and its socket stays open.

    Fix this →

Low

  1. The zero-byte read runs before every receive (SocketRlpxConnection.cs:227, inline).
    • During bulk transfer this adds a socket operation to each real read.
    • Doing the zero-byte read only after a short read, as Kestrel does, would keep the idle-peer memory benefit. This is optional.

Checked, nothing to report

  • Decoding:
    • Frames that arrive whole are authenticated before they are decrypted.
    • Split frames are decrypted into a private rented buffer and passed on only after the payload MAC passes.
    • Padded sizes stay block-aligned, and a block split across segments goes through the stack buffer.
    • After a failed MAC, the loop drains the pipe without decoding.
  • Handshake limit: length > ushort.MaxValue with the prefix matches DotNetty's LengthFieldBasedFrameDecoder.
  • Close and send:
    • Close drains the queue and enqueues under _sendLock, so no buffer leaks or is returned twice.
    • The send loop's dequeued item and batch buffer are returned in finally.
  • Writability: the watermarks (3,000,000 / 1,000,000) match 3.MB / 1.MB in SizeExtensions. The >= / <= comparisons match DotNetty.
  • Ordering: Snappy is decided when the processing thread handles the packet, so the Hello enables it before the next packet. A terminal error is queued after the frames already received.
  • Shutdown:
    • _shuttingDown under _lock covers late TryTrack calls.
    • Pending dials are awaited before the connections are snapshotted.
    • The processing threads stop only after the connections' loops have finished.
  • Refactor: RlpxErrorHandler keeps ExceptionCaught's behaviour, including base.ExceptionCaught for static/trusted peers and no disconnect on internal exceptions.
  • Comments: I saw no restating or generated-sounding comments in what I read; the in-line comments explain why.

Mergeable: not yet. Item 1 is Medium and hasn't been acknowledged.

@github-actions

github-actions Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Stateless guest cost

block steps Δ steps prover cost Δ cost
11957686 251,692,232 +0.000% 26,847,903,666 +0.000%
11962410 149,158,028 +0.000% 15,829,079,953 +0.000%
11962415 180,209,258 +0.000% 19,290,240,344 +0.000%
11962427 153,151,902 +0.000% 16,139,237,373 +0.000%
11962485 157,259,412 +0.000% 16,790,020,831 +0.000%
25526356 85,493,795 +0.000% 14,363,185,798 +0.000%
25532382 91,363,842 +0.000% 16,317,769,483 +0.000%
25532442 102,121,429 +0.000% 16,609,465,716 +0.000%
25532454 109,141,515 +0.000% 18,243,070,994 +0.000%
25532553 96,008,991 +0.000% 15,889,355,987 +0.000%
25532642 99,756,703 +0.000% 16,614,851,468 +0.000%
all 11 blocks 1,475,357,107 +0.000% 192,934,181,613 +0.000%
Variable cost by bucket, summed over shared blocks (excludes BASE)
bucket before after Δ
MAIN 91,472,140,634 91,472,140,634 +0.000%
OPCODES 19,320,551,101 19,320,551,101 +0.000%
PRECOMPILES 58,259,256,787 58,259,256,787 +0.000%
MEMORY 20,744,893,699 20,744,893,699 +0.000%

80abd409e225 (merge commit) · 11 pinned blocks · ziskemu is deterministic, so these figures are exact and any non-zero delta is real.

Compared against 14d42a1fef58.

@rubo
rubo marked this pull request as draft November 28, 2026 11:57
rubo added 7 commits November 28, 2026 13:13
…behind

A socket connection queued every decoded packet for its processing thread without limit, so a slow handler let a peer pin unbounded memory. The frame loop now pauses at 16 MB of received packets not yet handled; the pipe then fills and TCP slows the peer. A pause doesn't count toward the read timeout.
…on fails

A SessionCreated subscriber that threw escaped the accept loop and ended it, so the node stopped taking inbound peers, and the connection stayed tracked and open. The host now logs the failure and closes only that connection, as DotNetty closes only the channel whose handler failed. A dial that fails this way closes its connection the same way.
A shutdown that ran while Init was binding found no listener to close, and Init then published the socket and started an accept loop that exited at once, leaving the port bound. Init now publishes the listener under the host's lock only if no shutdown has started, and closes it otherwise.
…rrent sender

Senders check writability before serializing, so several could pass the check before one of them crossed the high watermark, and all of them were queued. Admission now checks writability again under the send lock and drops the packet, returning 0 as for a packet refused up front. A packet dropped by a close still counts as sent, as on DotNetty.
…transport tests

The Hello and Snappy test and the error ordering test slept 100 ms to let packets reach the processing thread's queue. They now wait for the connection's count of queued received bytes. The pending dial test is inconclusive rather than passing when the network refuses its address at once.
…ocket connection

Only a failing session activation was caught, so an exception elsewhere while setting up an inbound connection, such as in the inbound filter, still ended the accept loop. Setting up a connection now closes only that connection on any failure.
@rubo
rubo marked this pull request as ready for review November 29, 2026 15:58
@claude

claude Bot commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @rubo's task in 1m 14s —— View job


Re-review of PR #16473: RLPx transport on sockets and System.IO.Pipelines

  • Gather context (the previous review and rubo's replies)
  • Review the fixes since the last review (c428763 to 84a2d64)
  • Spot-check the connection and host code
  • Post findings

Summary: The Medium from the previous review is fixed. The commits since then are correct as far as I could tell. I found one new Low item and no Critical, High or Medium. I didn't build the code or run the tests; this is a read-only review.

Previous findings

  • Medium: a failure in Accept ended the accept loop. Fixed in c428763 and d86427a.
    • Accept now catches any failure during setup: it logs it, untracks the connection and closes it, or disposes the bare socket if no connection was built yet.
    • The fix has a regression test, Closes_only_the_inbound_connection_whose_setup_fails.
  • Low: the zero-byte read runs before every receive. Deferred, with a reason, to the follow-up that makes this transport the default. That's fine.

Low

  1. A dial whose session fails to activate still returns true (SocketRlpxHost.cs:381, inline).
    • StartSession closes the connection but returns void, so TryConnect logs OUT connected and reports success.
    • RlpxDialPolicy then skips the ENR alternate.
    • Nothing leaks, and the fix is optional.

Checked, nothing to report

  • Receive-queue bound (01bf9cc, e4fef21, 3573df5):
    • DecodeFrames checks IsReceiveQueueFull before each block and reports it through queueFull. A pause can't be lost if the processing thread frees capacity before the frame loop waits:
      • ReadFramesAsync advances without marking the bytes examined.
      • WaitForQueueCapacityAsync publishes its TCS and then checks again.
      • ReleaseQueuedBytes decrements before it reads the TCS.
    • Close completes any waiter.
    • IsReceiveQueueFull is false once the connection is closed. The remaining backlog stays bounded by the pipe's 1 MB pause threshold.
    • MinQueuedItemCharge is charged and released symmetrically, both for packets (through GetQueuedCharge) and for queued errors, including when TryEnqueue fails.
  • Read timeout during a pause (d9c9cff):
    • OnIdleTimer refreshes _lastReceive while _awaitingQueueCapacity is set, and the finally resets it when the pause ends.
    • The receive loop's FlushAsync(CancellationToken.None) can block while paused, but the timer doesn't cancel the receive during that time.
  • Listener bound after shutdown started (8474791, f9f307f):
    • Publishing _listener and starting the accept loop happen under _lock together with the _shuttingDown check. Otherwise Init disposes the listener and stops the threads.
    • The endpoint is read before publishing, so a concurrent shutdown can't dispose the listener first.
  • Shutdown ordering:
    • The accept loop and pending dials are awaited before the connections are snapshotted. Accept and StartSession are synchronous, so every connection that gets tracked has already started before the snapshot.
  • Failed activation:
    • RlpxSessionTracker.Activate has already registered the Closed continuation before the subscribers run. So the session that failed to activate is still marked disconnected and removed from the monitor once its connection closes.
  • Watermark drop (ededaf0):
    • TryAdmit checks writability again under _sendLock and returns the buffer when it drops a packet.
    • Enqueue already returned 0 for !IsWritable on master, so callers handle the dropped packet.
  • Comments: the added comments explain why, not what. I found no restating or generated-sounding text.

Mergeable: yes. The only open Medium was fixed, and the open Lows are optional.


Metrics.OutgoingConnections++;
if (_logger.IsTrace) _logger.Trace($"|NetworkTrace| Initializing {session:hide} channel");
StartSession(socket, connection, session);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low: a dial whose session fails to activate still reports success.

When _sessions.Activate throws, StartSession now closes the connection and returns. It returns void, though, so TryConnect goes on to log OUT connected and return true. RlpxDialPolicy.ConnectAsync then treats the primary endpoint as connected and never tries the ENR alternate. This doesn't leak anything, and an outbound subscriber failing is unlikely. If you want the result to be accurate, StartSession could return bool and TryConnect could return false on failure. Optional.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant